package com.ala4.oxcafe.serializer.attachment;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author PING
 * @date 2025/8/16 21:46
 */
public class FileKeyListDeserializer extends JsonDeserializer<String> implements ContextualDeserializer {

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {

        if (p.currentToken() != JsonToken.START_ARRAY) {
            return null;
        }

        List<String> keys = new ArrayList<>();

        while (p.nextToken() != JsonToken.END_ARRAY) {
            if (p.currentToken() == JsonToken.VALUE_STRING) {
                // 支持直接传递字符串数组
                keys.add(p.getText().trim());
            } else if (p.currentToken() == JsonToken.START_OBJECT) {
                // 处理对象格式 {"fileKey": "key", ...}
                String key = null;
                while (p.nextToken() != JsonToken.END_OBJECT) {
                    String fieldName = p.getCurrentName();
                    if ("fileKey".equals(fieldName)) {
                        p.nextToken();
                        key = p.getText().trim();
                    } else {
                        p.nextToken();
                        p.skipChildren();
                    }
                }
                if (key != null && !key.isEmpty()) {
                    keys.add(key);
                }
            }
        }

        return String.join(",", keys);
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        return this;
    }
}
